﻿using System;
using System.Threading;

namespace BlueMarble.Genesis.Infrastructure.Security
{
    public class Membership
    {
        protected MembershipServiceReference.RoleService membershipService;

        public Membership()
        {
            this.connectService();
        }

#if !SILVERLIGHT
        public void GetRolesForCurrentUser()
#else
        public void GetRolesForCurrentUser()
#endif
        {
#if !SILVERLIGHT
            string[] currentRoles = null;
#else
            System.Collections.ObjectModel.ObservableCollection<string> currentRoles = null;
#endif

            ManualResetEvent resetEvent = new ManualResetEvent(false);

            IAsyncResult asyncResult = this.membershipService.BeginGetRolesForCurrentUser(v =>
            {
                try { currentRoles = this.membershipService.EndGetRolesForCurrentUser(v); }
                finally { resetEvent.Set(); }
            }, null);

            ThreadPool.QueueUserWorkItem((o) =>
            {
                WaitHandle.WaitAll(new WaitHandle[] { resetEvent });

                if (this.GetRolesForCurrentUserCompleted != null)
                {
                    this.GetRolesForCurrentUserCompleted(currentRoles);
                }
            });
        }

        public void IsCurrentUserInRole(string Role)
        {
            bool userInRole = false;

            ManualResetEvent resetEvent = new ManualResetEvent(false);

            IAsyncResult asyncResult = this.membershipService.BeginIsCurrentUserInRole(Role, v =>
            {
                try { userInRole = this.membershipService.EndIsCurrentUserInRole(v); }
                finally { resetEvent.Set(); }
            }, null);

            ThreadPool.QueueUserWorkItem((o) =>
            {
                WaitHandle.WaitAll(new WaitHandle[] { resetEvent });

                if (this.IsCurrentUserInRoleCompleted != null)
                {
                    this.IsCurrentUserInRoleCompleted(userInRole);
                }
            });
        }

        protected void connectService()
        {
            if (this.membershipService == null)
            {
                this.membershipService = new MembershipServiceReference.RoleServiceClient();
            }
        }

        public event GetRolesForCurrentUserEventHandler GetRolesForCurrentUserCompleted;
        public event IsCurrentUserInRoleEventHandler IsCurrentUserInRoleCompleted;
    }
    
#if !SILVERLIGHT
    public delegate void GetRolesForCurrentUserEventHandler(string[] Roles);
#else
    public delegate void GetRolesForCurrentUserEventHandler(System.Collections.ObjectModel.ObservableCollection<string> Roles);
#endif
    public delegate void IsCurrentUserInRoleEventHandler(bool UserInRole);
}
